<?php

namespace Admin\Controller;

use Think\Controller;
use Common\Service\Dictionary;

class OrderController extends CommonController
{
    public function index()
    {
        $map = [];
        if (IS_GET) {
            $order_no = I('get.order_no');
            $name = I('get.name');
            $created_at = I('get.created_at');
            $status = $_GET['status'];
//            p($status);exit;

            if (!empty($order_no)) {
                $map['order_no'] = array('like', "%" . $order_no . "%");
            }
            if (!empty($name)) {
                $map['b.name'] = array('like', "%" . $name . "%");   //按手机号
            }

            //按统计时间
            if (!empty($created_at)) {
                $time = explode(" ~ ", $created_at);  //把字符串转换成数组
//                p($time);exit;
                $times[] = strtotime($time[0] . ' 00:00:00'); //这里单引号前面要打一空格
                $times[] = strtotime($time[1] . ' 23:59:59');

                $map['created_at'] = array('between', $times);
            }
            if (!empty($status)) {
                $map['status'] = array('like', "%" . $status . "%"); //按订单状态
            }
        }


        $count = $this->order->count(); //查出满足要求的记录数
        $Page = new \Common\Util\Page($count, 5);// 实例化分页类 传入总记录数和每页显示的记录数
        $orders = $this->order->alias('a')->order('created_at desc')->field('a.*,b.area,b.detail,b.tel,b.name')
            ->join('address AS b ON b.id=a.address_id', 'LEFT')
            ->where($map)->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        //        foreach ($orders as &$order){
//            $order['address'] = $this->address->where($map)->where("id = '$order[address_id]'")->find();
//        }
        $pages = $Page->show();//分页显示输出

        //调用静态方法查出所有订单状态
        $orderStatus = Dictionary::orderStatus();
        $this->assign(compact('orders', 'pages', 'count','orderStatus'));
        $this->display();
    }

    public function show()
    {
        $id = I('get.id');
        $order = $this->order->where("id='$id'")->find();
        $address_id =$order['address_id'];
        $address = $this->address->find($address_id);

        //商品信息 2表连表查询(a:product b:order_product,c:order) 当用户选择多个商品一起购买时，商品订单表会同时插入多条数据
        $products= $this->product->alias('a')
            ->field('a.name,a.price,b.number,a.price*b.number as total,c.total_price')//这里计算商品小计
            ->join('order_product AS b ON b.product_id=a.id', 'LEFT')
            ->join('orders AS c ON c.id=b.order_id', 'LEFT')
            ->where(array('b.order_id' => $id))
            ->select();

        $this->assign(compact('address','order','products'));
        $this->display();

    }
}